package com.campus.help.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.help.common.PageResult;
import com.campus.help.common.Result;
import com.campus.help.common.ResultCode;
import com.campus.help.entity.Student;
import com.campus.help.entity.School;
import com.campus.help.service.StudentService;
import com.campus.help.service.SchoolService;
import com.campus.help.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 学生管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/students")
public class AdminStudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 分页查询学生列表
     */
    @GetMapping
    public Result<PageResult<Student>> getStudentList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Long schoolId,
            @RequestParam(required = false) String status,
            HttpServletRequest request) {

        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            Page<Student> page = new Page<>(current, size);
            IPage<Student> studentPage = studentService.getStudentPage(page, studentId, name, schoolId, status);

            PageResult<Student> pageResult = new PageResult<>(
                studentPage.getCurrent(),
                studentPage.getSize(),
                studentPage.getTotal(),
                studentPage.getRecords()
            );

            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询学生列表失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据ID查询学生详情
     */
    @GetMapping("/{id}")
    public Result<Student> getStudentById(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            Student student = studentService.getById(id);
            if (student == null) {
                return Result.error(ResultCode.NOT_FOUND);
            }

            return Result.success(student);
        } catch (Exception e) {
            log.error("查询学生详情失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 添加学生
     */
    @PostMapping
    public Result<Void> addStudent(@RequestBody Student student, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            boolean success = studentService.addStudent(student);
            if (success) {
                return Result.success();
            } else {
                return Result.error(ResultCode.SYSTEM_ERROR);
            }
        } catch (RuntimeException e) {
            log.error("添加学生失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("添加学生失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 更新学生
     */
    @PutMapping("/{id}")
    public Result<Void> updateStudent(@PathVariable Long id, @RequestBody Student student, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            student.setId(id);
            boolean success = studentService.updateStudent(student);
            if (success) {
                return Result.success();
            } else {
                return Result.error(ResultCode.SYSTEM_ERROR);
            }
        } catch (RuntimeException e) {
            log.error("更新学生失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("更新学生失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 删除学生
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteStudent(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            boolean success = studentService.deleteStudent(id);
            if (success) {
                return Result.success();
            } else {
                return Result.error(ResultCode.SYSTEM_ERROR);
            }
        } catch (RuntimeException e) {
            log.error("删除学生失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("删除学生失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 更新学生状态
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateStudentStatus(@PathVariable Long id, @RequestBody StatusUpdateRequest statusRequest, HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            boolean success = studentService.updateStudentStatus(id, statusRequest.getStatus());
            if (success) {
                return Result.success();
            } else {
                return Result.error(ResultCode.SYSTEM_ERROR);
            }
        } catch (RuntimeException e) {
            log.error("更新学生状态失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("更新学生状态失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取学校列表
     */
    @GetMapping("/schools")
    public Result<List<School>> getSchools(HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!validateAdminToken(request)) {
                return Result.error(ResultCode.UNAUTHORIZED);
            }

            List<School> schools = schoolService.getActiveSchools();
            return Result.success(schools);
        } catch (Exception e) {
            log.error("获取学校列表失败", e);
            return Result.error(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 验证管理员token
     */
    private boolean validateAdminToken(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return false;
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            return tokenInfo != null && "admin".equals(tokenInfo.getType());
        } catch (Exception e) {
            log.error("验证管理员token失败", e);
            return false;
        }
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }

    /**
     * 状态更新请求类
     */
    public static class StatusUpdateRequest {
        private String status;

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }
    }
}
